<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/10/26
 * Time: 5:39 PM
 */

namespace App\HttpController\Api\Common;

use App\HttpController\Api\ApiBase;
use swoole\Coroutine as co;

class Helpers extends ApiBase
{
    /*并发查询函数demo
     WaitGroup
    */
    function ConcurrentQuery(): void
    {
        go(function () {
            $ret = [];
            $wait = new \EasySwoole\Component\WaitGroup();

            $wait->add();
            // 启动第 1 个协程
            go(function () use ($wait, &$ret) {
                // 模拟耗时任务 1
                co::sleep(5);
                $ret[] = 2;
                $wait->done();
            });

            $wait->add();
            // 启动第 2 个协程
            go(function () use ($wait, &$ret) {
                // 模拟耗时任务 2
                co::sleep(2);
                $ret[] = 3;
                $wait->done();
            });
            // 挂起当前协程，等待所有任务完成后恢复
            $wait->wait();
            // 这里 $ret 包含了 2 个任务执行结果
            var_dump($ret);
        });
    }

}